package com.itheima.common;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GobalException {
    //写入全局异常注释
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R getException(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已经存在";
            return R.error(msg);
        }

        return R.error("出了某种错误");
    }
    @ExceptionHandler(CustomException.class)
    public R getCusttomException(CustomException ex){

        return R.error(ex.getMessage());
    }
}
